import { useEffect, useState } from "react";
import { Button, Space, Select, Input, List, Modal } from "antd";
import { LocalStorage } from "./cacheTodo";
import { v1 as uuid } from "uuid";
import "./index.css";

interface Todo {
  id: string;
  text: string;
  completed: boolean;
}

enum TodoFilter {
  ALL = "all",
  ACTIVE = "active",
  COMPLETED = "completed",
}
const local = new LocalStorage<Todo>();
const initTodos = local.getLocal();
function TodoList() {
  const [todos, setTodos] = useState<Todo[]>(initTodos);
  const [text, setText] = useState("");
  const [filterStatus, setFilterStatus] = useState(TodoFilter.ALL);

  const [modal, contextHolder] = Modal.useModal();

  const filterTodos = todos.filter((todo) => {
    if (filterStatus === TodoFilter.ACTIVE) {
      return !todo.completed;
    } else if (filterStatus === TodoFilter.COMPLETED) {
      return todo.completed;
    }
    return true;
  });

  useEffect(() => {
    console.log("useEffect执行------------");
    local.setLocal(todos);
  }, [todos]);

  const addTodo = () => {
    if (text.length) {
      setTodos([
        ...todos,
        {
          id: uuid(),
          text,
          completed: false,
        },
      ]);
      setText("");
    }
  };
  const completeTodo = (todo: Todo) => {
    setTodos(
      todos.map((t) => {
        if (t.id === todo.id) {
          return { ...t, completed: true };
        } else {
          return t;
        }
      })
    );
  };
  const delTodo = (todo: Todo) => {
    modal.confirm({
      title: "确认删除",
      content: `是否确认删除待办事项：${todo.text}`,
      onOk: () => {
        setTodos(todos.filter((t) => t.id !== todo.id));
      },
      onCancel: () => {
        console.log("取消删除");
      },
    });
  };

  const handleChange = (value: TodoFilter) => {
    setFilterStatus(value);
  };

  const actionBtns = (todo: Todo) => {
    const btns = [
      <Button type="primary" color="danger" onClick={() => delTodo(todo)}>
        删除
      </Button>,
    ];
    if (!todo.completed) {
      btns.unshift(
        <Button type="primary" onClick={() => completeTodo(todo)}>
          完成
        </Button>
      );
    }
    return btns;
  };

  return (
    <>
      <div>{contextHolder}</div>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Select
            defaultValue={TodoFilter.ALL}
            style={{ width: 120 }}
            onChange={handleChange}
            options={[
              { value: TodoFilter.ALL, label: "全部" },
              { value: TodoFilter.ACTIVE, label: "进行中" },
              { value: TodoFilter.COMPLETED, label: "已完成" },
            ]}
          />

          <Input
            placeholder="请输入待办事项"
            style={{ width: 200 }}
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                addTodo();
              }
            }}
          />
          <Button type="primary" onClick={addTodo}>
            添加
          </Button>
        </Space>
      </div>
      <List
        bordered
        dataSource={filterTodos}
        renderItem={(item, index) => (
          <List.Item actions={actionBtns(item)}>
            <span className={item.completed ? "completed" : ""}>
              {index + 1}、{item.text}
            </span>
          </List.Item>
        )}
        footer={
          todos.length > 0 ? (
            <span>共计 {todos.length} 条待办事项</span>
          ) : (
            <span>暂无待办事项</span>
          )
        }
      />
    </>
  );
}

export default TodoList;
